package com.hz.foodstalls.interceptor;

import com.hz.foodstalls.model.Admin;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.ext.plugin.shiro.AuthzHandler;
import com.jfinal.ext.plugin.shiro.ShiroKit;
import com.jfinal.ext.plugin.shiro.ShiroMethod;
import com.jfinal.kit.StrKit;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by foodstalls on 2016/2/17.
 */
public class AdminInterceptor implements Interceptor {
    private String breadHomeMethod = "/index";//面包屑首页

    public Map<String, String> pageTitleBread() {
        Map<String, String> pageTitleBread = new HashMap<String, String>();
        pageTitleBread.put("indexTitle", "");
        pageTitleBread.put("editTitle", "");
        return pageTitleBread;
    }

    @Override
    public void intercept(Invocation invocation) {
        Controller controller = invocation.getController();
        if (ShiroMethod.notAuthenticated()) {
            controller.redirect("/admin/login");
        } else {
            AuthzHandler ah = ShiroKit.getAuthzHandler(invocation.getControllerKey());
            Class<? extends Controller> oc = controller.getClass();
            // 存在访问控制处理器。
            if (ah != null) {
                try {
                    // 执行权限检查
                    ah.assertAuthorized();
                    String username = controller.getSessionAttr("username");
                    Admin admin = Admin.dao.findFirst("select * from admin where username=?", username);
                    controller.setAttr("treeviews", controller.getSessionAttr("treeviews"));//设置动态菜单
                    Method method = oc.getMethod("getPageTitleBread");
                    Object o = method.invoke(controller);
                    //过滤
                    String action = invocation.getActionKey();
                    Map<String, String> map = (HashMap<String, String>) o;
                    map.put("breadHomeMethod", breadHomeMethod);//首页地址（"/index"）
                    map.put("department", admin.getDepartment());//导航栏
                    map.put("default", "舟山汇智智能科技有限公司");
                    if (action.equals(invocation.getControllerKey())) {//一级菜单
                        map.put("nowBread", map.get("indexTitle"));
                    } else {//二级菜单
                        map.put("url", invocation.getControllerKey());//上一级URL
                        map.put("pageTitle", map.get("indexTitle"));//上一级标题
                        map.put("nowBread", map.get("editTitle"));//当前标题
                    }
                    controller.setAttr("pageTitleBread", map);//设置标题和面包屑
                } catch (UnauthenticatedException lae) {
                    // RequiresGuest，RequiresAuthentication，RequiresUser，未满足时，抛出未经授权的异常。
                    // 如果没有进行身份验证，返回HTTP401状态码
                    invocation.getController().renderError(401);
                    return;
                } catch (AuthorizationException ae) {
                    // RequiresRoles，RequiresPermissions授权异常
                    // 如果没有权限访问对应的资源，返回HTTP状态码403。
                    invocation.getController().renderError(403);
                    return;
                } catch (NoSuchMethodException es) {
                    controller.setAttr("pageTitleBread", pageTitleBread());
                } catch (Exception e) {
                    // 出现了异常，应该是没有登录。
                    invocation.getController().renderError(401);
                    return;
                }
            }
            invocation.invoke();
        }
    }
}
